import { useEffect, useState } from "react";

let ws;
let timoutId
let intervalId 
function SocketDemo() {
   const [msgList,setMsgList] = useState([])
   const parseStr = (obj)=>JSON.stringify(obj)
    useEffect(()=>{
       createWs()
        return ()=>{
            clearInterval(intervalId)
        }
    },[])

    const createWs = ()=>{
         ws = new WebSocket('ws://localhost:9001')
        ws.onopen=function(e){
            console.log('onopen',e);
        }
        ws.onmessage = function(e) {
            const data = JSON.parse(e.data)
            if(data?.event==='heartBeat'){
                clearTimeout(timoutId)
            } else{
                setMsgList(pre=>[...pre,data])
            }
        }

    //  每隔5s发一次心跳检测消息
    intervalId = setInterval(
        ()=>{
            timoutId = setTimeout(()=>{
                console.log('检测不到服务端的回应，超时了');
                ws.close()
                ws = null;
                 clearInterval(intervalId)
                  clearTimeout(timoutId)
                // 断线后重新连接 创建一个新的
               setTimeout(createWs,5000)
            }, 3000)
             ws.send(parseStr({event:'heartBeat' ,content:'ping'}))
        },
        2000)
    }
    return ( 
        <>
        {msgList.map((item,index)=>(<div key={index}> {item.content}</div>))}
        <div><button type="button" onClick={()=>{
            ws.send(JSON.stringify({event:'login',name:'lixin'}))
        }}>发个消息</button></div>
        </>
     );
}

export default SocketDemo;